﻿using IoTBrowser.Helper;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace IoTBrowser
{
    /// <summary>
    /// LoadingWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LoadingWindow : Window
    {
        string bit= Environment.Is64BitOperatingSystem ? "x64":"x86";
        public LoadingWindow()
        {
            InitializeComponent();
            Closed += LoadingWindow_Closed;
        }

        private void LoadingWindow_Closed(object sender, EventArgs e)
        {
            App.Current.Shutdown();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            pbMain.Visibility = Visibility.Hidden;
            Task.Run(() => {
                try
                {
                    LocalStart();
                }
                catch (Exception ex)
                {
                    Dispatcher.Invoke(() =>
                    {
                        MessageBox.Show(ex.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                        this.Close();
                    });
                }
            });
        }
        private void LocalStart() {
            ShowMsg("启动中...");
            if (!Environment.Is64BitOperatingSystem)
            {
                MessageBox.Show("不支持32位操作系统","提示",MessageBoxButton.OK,MessageBoxImage.Error);
                Exit();
                return;
            }

            if (!HaveInstallVc())
            {
                var r=MessageBox.Show("检测到缺少C++组件，点击“确定”安装后再打开","提示",MessageBoxButton.OKCancel,MessageBoxImage.Asterisk);
                if (r == MessageBoxResult.OK)
                {
                    ShowMsg("请安装C++运行时后，重启应用！");
                    var cSetup = IoTBrowser.Properties.Resources.vcredist_x64;
                    var cInstallFile = AppDomain.CurrentDomain.BaseDirectory + "vcredist_x64.exe";
                    if (!System.IO.File.Exists(cInstallFile))
                    {
                        System.IO.File.WriteAllBytes(cInstallFile, cSetup);
                    }
                    System.Diagnostics.Process.Start(cInstallFile);
                }
            }
            var appDirName = "app_x64";
            var installDir = AppDomain.CurrentDomain.BaseDirectory + appDirName + "\\";
            var runFile = installDir + "DDS.Browser.exe";
            // 测试模式
            if (Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["isTest"]))
            {
                installDir = installDir.Replace("\\bin\\Debug", "");
                runFile = installDir + "DDS.Browser.exe";
            }
            else
            {
                var b = IoTBrowser.Properties.Resources.app_x64;
                if (!System.IO.Directory.Exists(installDir))
                {
                    System.IO.Directory.CreateDirectory(installDir);
                }
                var installFile = installDir + appDirName + ".zip";
                if (!System.IO.File.Exists(installFile))
                {
                    ShowMsg("初始化中...");
                    System.IO.File.WriteAllBytes(installFile, b);

                    ZipHelper.Decompress(installFile, installDir);
                }
            }
            var process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = runFile;
            startInfo.WorkingDirectory = installDir;
            process.StartInfo = startInfo;
            process.Start();
            Exit();
        }
        public void Exit() {

            Environment.Exit(0);
        }
        public void ShowMsg(string msg) {
            Dispatcher.Invoke(() =>
            {
                lblTip.Content = msg;
            });
        }

        private void SetOpenStart(bool isOpenStart)
        {
            string R_startPath = Assembly.GetExecutingAssembly().Location;
            if (isOpenStart)
            {
                RegistryKey R_local = Registry.LocalMachine;
                RegistryKey R_run = R_local.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                R_run.SetValue("IoTBrowser", R_startPath);
                R_run.Close();
                R_local.Close();
            }
            else
            {
                try
                {
                    RegistryKey R_local = Registry.LocalMachine;
                    RegistryKey R_run = R_local.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                    R_run.DeleteValue("IoTBrowser", false);
                    R_run.Close();
                    R_local.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("您需要管理员权限修改", "提示", MessageBoxButton.OK);
                }
            }
        }

        [DllImport("msi.dll")]
        private static extern INSTALLSTATE MsiQueryProductState(string product);
        public static INSTALLSTATE GetProcuct(string product)
        {
            INSTALLSTATE state = MsiQueryProductState(product);
            return state;
        }
        public enum INSTALLSTATE
        {
            INSTALLSTATE_NOTUSED = -7,  // component disabled
            INSTALLSTATE_BADCONFIG = -6,  // configuration data corrupt
            INSTALLSTATE_INCOMPLETE = -5,  // installation suspended or in progress
            INSTALLSTATE_SOURCEABSENT = -4,  // run from source, source is unavailable
            INSTALLSTATE_MOREDATA = -3,  // return buffer overflow
            INSTALLSTATE_INVALIDARG = -2,  // invalid function argument
            INSTALLSTATE_UNKNOWN = -1,  // unrecognized product or feature
            INSTALLSTATE_BROKEN = 0,  // broken
            INSTALLSTATE_ADVERTISED = 1,  // advertised feature
            INSTALLSTATE_REMOVED = 1,  // component being removed (action state, not settable)
            INSTALLSTATE_ABSENT = 2,  // uninstalled (or action state absent but clients remain)
            INSTALLSTATE_LOCAL = 3,  // installed on local drive
            INSTALLSTATE_SOURCE = 4,  // run from source, CD or net
            INSTALLSTATE_DEFAULT = 5,  // use default, local or source
        }
        public static bool HaveInstallVc()
        {
            //Visual C++ 2013 Redistributable Package (x86 12.0.21005)
            //{13A4EE12-23EA-3371-91EE-EFB36DDFFF3E} and {F8CFEB22-A2E7-3971-9EDA-4B11EDEFC185}
            //Visual C++ 2013 Redistributable Package (x64)
            //{929FBD26-9020-399B-9A7A-751D61F0B942} and {A749D8E6-B613-3BE3-8F5F-045C84EBA29B}
            //INSTALLSTATE state = MsiQueryProductState("{13A4EE12-23EA-3371-91EE-EFB36DDFFF3E}");
            if (MsiQueryProductState("{13A4EE12-23EA-3371-91EE-EFB36DDFFF3E}") == INSTALLSTATE.INSTALLSTATE_DEFAULT)
                return true;
            else if (MsiQueryProductState("{F8CFEB22-A2E7-3971-9EDA-4B11EDEFC185}") == INSTALLSTATE.INSTALLSTATE_DEFAULT)
                return true;
            else if (MsiQueryProductState("{929FBD26-9020-399B-9A7A-751D61F0B942}") == INSTALLSTATE.INSTALLSTATE_DEFAULT)
                return true;
            else if (MsiQueryProductState("{A749D8E6-B613-3BE3-8F5F-045C84EBA29B}") == INSTALLSTATE.INSTALLSTATE_DEFAULT)
                return true;
            else if (MsiQueryProductState("{6E8E85E8-CE4B-4FF5-91F7-04999C9FAE6A}") == INSTALLSTATE.INSTALLSTATE_DEFAULT)
                return true;// Visual C++ 2005 Redistributable Package (x64)
            else if (MsiQueryProductState("{071C9B48-7C32-4621-A0AC-3F809523288F}") == INSTALLSTATE.INSTALLSTATE_DEFAULT)
                return true;// Visual C++ 2005 SP1 Redistributable Package (x64)
            else if (MsiQueryProductState("{350AA351-21FA-3270-8B7A-835434E766AD}") == INSTALLSTATE.INSTALLSTATE_DEFAULT)
                return true;// Visual C++ 2008 Redistributable Package (x64)
            else if (MsiQueryProductState("{8220EEFE-38CD-377E-8595-13398D740ACE}") == INSTALLSTATE.INSTALLSTATE_DEFAULT)
                return true;// Visual C++ 2008 SP1 Redistributable Package (x64)
            else if (MsiQueryProductState("{DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}") == INSTALLSTATE.INSTALLSTATE_DEFAULT)
                return true;// Visual C++ 2010 Redistributable Package (x64)
            else if (MsiQueryProductState("{ad8a2fa1-06e7-4b0d-927d-6e54b3d31028}") == INSTALLSTATE.INSTALLSTATE_DEFAULT)
                return true;// Visual C++ 2005 Redistributable Package (x64)
            else
                return false;
        }
    }
}
